<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form action="">
        <table>
            <caption>
                <h2>登录</h2>
            </caption>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td>
                    <input type="password" name="password" id="">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit">
                </td>
            </tr>
        </table>
    </form>
</body>
<script src="./js/utils.js"></script>
<script>
    var form = document.querySelector('form')
    var username = document.querySelector('[name = "username"]')
    var password = document.querySelector('[name = "password"]')
    form.addEventListener('submit', onsubmit)

    function onsubmit() {
        //阻止默认行为
        window.event.returnValue = false
        //验证账号
        if (username.value.trim() === '') {
            alert('账号不能为空')
            return false
        }
        //验证密码
        if (password.value.trim() === '') {
            alert('密码不能为空')
            return false
        }
        //ajax请求
        var xhr = new XMLHttpRequest;
        xhr.open('post', 'http://localhost:8888/users/login');
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        xhr.send(`username=${username.value}&password=${password.value}`)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    var res = xhr.responseText;
                    res = JSON.parse(res)
                    // console.log(res);
                    var {
                        code,
                        message,
                        user:{id:userId},
                        token
                    } = res
                    if (code === 1) {
                        alert(message)
                        //cookie具有时效性,两小时有效
                        setCookie('username', username.value, 2000)
                        setCookie('userId', userId, 7200)
                        localStorage.setItem('token', token)
                        var url = localStorage.getItem('url')
                        if (url) {
                            // 在跳转之前要将本地存储中的地址删除掉
                            localStorage.removeItem('url')
                            location.href = url
                        } else
                            location.href = './index.html'
                    } else {
                        alert(message)
                    }
                }
            }
        }
    }
</script>

</html>